import network
# 导入必要的库
import network
import usocket as socket
import time
import ubinascii
import uos
import _thread


connect_status_4g = False
connect_status_eth = False

# 定义TCP服务器参数
SERVER_IP = '192.168.1.94'
SERVER_PORT = 80
def tcprecv(s):    
    while True:        
        try:            
            recvdata = s.recv(255)        
        except OSError:            
            print('TCP OSError recv')            
            break        
        except:            
            break        
        if len(recvdata) > 0:            
            print(f'recv: {recvdata}')        
    time.sleep(1)

#wifi连接-----------------------------------------------------------
def connect_wifi(ssid,pwd):
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    time.sleep(2)
    wlan.connect(ssid, pwd)
    while not wlan.isconnected():
        pass
    print('wifi connected: ', wlan.ifconfig())

if __name__ == '__main__':
    #connect_eth()  #以太网
    connect_wifi("root824","zgt88888")  #wifi
    #connect_4g()    #4G
    # 创建UDP客户端socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect((SERVER_IP,SERVER_PORT))
    except OSError as e:
        print(f"连接服务费失败{}",e)
        
    _thread.start_new_thread(tcprecv, (sock,))  
    while True:
        time.sleep(1)
        try:
            response = 'Hello from ESP32 TCP server!'
            sock.send(response.encode())
            print('------')
        except:
            print('send  fail------')

